#include "viml/compiler.h"
#include "viml/vm.h"
#include <iostream>
#include <sstream>
#include <gtest/gtest.h>

namespace viml {

class EchoSpaceSyntaxTest : public ::testing::Test {
protected:
    Compiler compiler;
    VM vm;
    
    void SetUp() override {
        // 重置编译器和虚拟机状态
        compiler.reset();
        vm.reset();
    }
};

// 测试echo语句使用空格分隔元素（不使用逗号）
TEST_F(EchoSpaceSyntaxTest, EchoSpaceSeparatedElements) {
    std::string source = "echo \"Hello\" \"World\" \"Test\"";
    
    // 重定向标准输出到字符串流
    std::stringstream buffer;
    std::streambuf* old = std::cout.rdbuf(buffer.rdbuf());
    
    try {
        // 编译并执行
        auto bytecode = compiler.compile(source);
        vm.execute(bytecode);
        
        // 恢复标准输出
        std::cout.rdbuf(old);
        
        // 检查输出结果
        std::string output = buffer.str();
        std::cout << "Output: '" << output << "'" << std::endl;
        
        // 验证输出内容和格式
        EXPECT_EQ(output, "Hello World Test\n");
    } catch (...) {
        // 恢复标准输出
        std::cout.rdbuf(old);
        FAIL() << "Exception thrown during execution";
    }
}

// 测试混合使用逗号和空格分隔的echo语句
TEST_F(EchoSpaceSyntaxTest, EchoMixedCommaAndSpaceSeparatedElements) {
    std::string source = "echo \"Mixed\", 1 2, 3";
    
    // 重定向标准输出到字符串流
    std::stringstream buffer;
    std::streambuf* old = std::cout.rdbuf(buffer.rdbuf());
    
    try {
        // 编译并执行
        auto bytecode = compiler.compile(source);
        vm.execute(bytecode);
        
        // 恢复标准输出
        std::cout.rdbuf(old);
        
        // 检查输出结果
        std::string output = buffer.str();
        std::cout << "Output: '" << output << "'" << std::endl;
        
        // 验证输出内容和格式
        EXPECT_EQ(output, "Mixed 1 2 3\n");
    } catch (...) {
        // 恢复标准输出
        std::cout.rdbuf(old);
        FAIL() << "Exception thrown during execution";
    }
}

// 测试单个元素的echo语句
TEST_F(EchoSpaceSyntaxTest, EchoSingleElement) {
    std::string source = "echo \"Single\"";
    
    // 重定向标准输出到字符串流
    std::stringstream buffer;
    std::streambuf* old = std::cout.rdbuf(buffer.rdbuf());
    
    try {
        // 编译并执行
        auto bytecode = compiler.compile(source);
        vm.execute(bytecode);
        
        // 恢复标准输出
        std::cout.rdbuf(old);
        
        // 检查输出结果
        std::string output = buffer.str();
        std::cout << "Output: '" << output << "'" << std::endl;
        
        // 验证输出内容
        EXPECT_EQ(output, "Single\n");
    } catch (...) {
        // 恢复标准输出
        std::cout.rdbuf(old);
        FAIL() << "Exception thrown during execution";
    }
}

} // namespace viml